package com.tools.scanner.utils

import android.content.Context
import android.net.Uri
import com.google.android.gms.tasks.Task
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.latin.TextRecognizerOptions
import com.tools.scanner.bean.OcrItemInfo

object TextOcrUtil {

    private val textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
//    private val textRecognizer = TextRecognition.getClient(ChineseTextRecognizerOptions.Builder().build())

    fun performOcr(
        context: Context,
        uri: Uri,
        success: (List<OcrItemInfo>) -> Unit,
        failure: (e: Exception) -> Unit
    ) {
        val image = InputImage.fromFilePath(context, uri)
        val task: Task<Text> = textRecognizer.process(image)
        task.addOnSuccessListener { visionText ->
            success(extractTextBlocks(visionText))
        }.addOnFailureListener { e ->
            failure(e)
        }

    }

    private fun extractTextBlocks(text: Text): List<OcrItemInfo> {
        val resultList = mutableListOf<OcrItemInfo>()

        text.textBlocks.forEach { block ->
            resultList.add(
                OcrItemInfo(
                    block.cornerPoints,
                    block.lines,
                    block.boundingBox,
                    block.text
                )
            )
        }

        return resultList
    }
}